package sw6.visualschedule.adminpanel;

import com.commonsware.cwac.tlv.TouchListView;

import sw6.visualschedule.R;
import sw6.visualschedule.entities.ScheduleActivity;
import sw6.visualschedule.entities.Step;
import sw6.visualschedule.persistence.ScheduleActivityRepo;
import sw6.visualschedule.persistence.StepRepo;
import tools.BundleHelper;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class ActivityStepList extends ListActivity {

    private class IconicAdapter extends ArrayAdapter<Step> {
        IconicAdapter() {
            super(ActivityStepList.this, R.layout.touchlist_item, mSteps);
        }
        
        public View getView(final int position, final View convertView, final ViewGroup parent) {
            View row = convertView;
            
            if (row == null) {                                                    
                final LayoutInflater inflater = getLayoutInflater();
                row = inflater.inflate(R.layout.touchlist_item, parent, false);
            }
            
            final TextView label = (TextView)row.findViewById(R.id.label);            
            label.setText(mSteps.get(position).getTitle());

            return row;
        }
    }
    private transient IconicAdapter adapter = null;
    
    private transient ScheduleActivity mActivity;
    private transient List<Step> mSteps;
    
    private transient StepRepo mStepService;
    
	private final transient TouchListView.DropListener onDrop = new TouchListView.DropListener() {
        @Override
        public void drop(final int from, final int to) {
            final Step item = adapter.getItem(from);
            
            if (from < to) {
                adapter.remove(item);
                adapter.insert(item, to);
                
                final List<Step> stepsToMove = mSteps.subList(from, to);
                for (Step s : stepsToMove) {
                    s.setOrder(s.getOrder() - 1);
                    mStepService.update(s);
                }
            } else {
                final List<Step> stepsToMove = mSteps.subList(to, from);
                for (Step s : stepsToMove) {
                    s.setOrder(s.getOrder() + 1);
                    mStepService.update(s);
                }
                
                adapter.remove(item);
                adapter.insert(item, to);
            }
            
            item.setOrder(to);
            mStepService.update(item);
        }
    };
    
    @Override
    public void onCreate(final Bundle bundle) {
        super.onCreate(bundle);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activitysteplist);
    
        mStepService = new StepRepo(this);
        ScheduleActivityRepo activityService = new ScheduleActivityRepo(this);
        
        final TouchListView tlv = (TouchListView)getListView();
        tlv.setDropListener(onDrop);
        //tlv.setRemoveListener(onRemove);
        
        final int activityId = getIntent().getIntExtra(BundleHelper.ACTIVITY_ID, -1);
       
        mActivity = activityService.getById(activityId);
        setTitle(getString(R.string.adm_activitysteplist_title, mActivity.getTitle()));
        
        //Create long click listener on listactivity's listview
		getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
		    @Override
		    public boolean onItemLongClick(final AdapterView<?> adapter, final View view, final int pos, final long itemId) {
		        //Call click handler method added to ListActivity
		    	return onLongListItemClick(view, pos, itemId);
		    }
		});
    }
    
    /**
     * @see super
     */
    @Override
	public boolean onCreateOptionsMenu(final Menu menu) {
	    final MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.steps_pref, menu);
	    return true;
	}
	
    /**
     * @see super
     */
	@Override
	public boolean onOptionsItemSelected(final MenuItem item) {
	    boolean result;
	    
	    if (item.getItemId() == R.id.add_step) {
	    	final Intent intent = new Intent().setClass(this, StepConstructor.class);
	    	intent.putExtra(BundleHelper.ACTIVITY_ID, getIntent().getIntExtra(BundleHelper.ACTIVITY_ID, -1));
	    	startActivity(intent);
	        result = true;
	    } else {
	        result = super.onOptionsItemSelected(item);
	    }
	    
	    return result;
	}	
	
	private void deleteStep(final Step step) {
		//Remove from list
		adapter.remove(step);
		adapter.notifyDataSetChanged();
		
		//Remove from database
    	mStepService.delete(step);

    	//User feedback
    	Toast.makeText(this, "Deleted " + step.getTitle(), Toast.LENGTH_SHORT).show();
	}
	
	@Override
	protected void onListItemClick(final ListView list, final View view, final int position, final long itemId) {
		super.onListItemClick(list, view, position, itemId);
		
		final Step selectedStep = mSteps.get(position);
		
		final Intent intent = new Intent(this, StepConstructor.class);
		intent.putExtra(BundleHelper.STEP_ID, selectedStep.getId());
		startActivity(intent);
	}
	
	protected boolean onLongListItemClick(final View view, final int pos, final long itemId) {
		//Get Step
		final Step selectedStep = mSteps.get(pos);		
		
		//Show confirm dialog
		new AlertDialog.Builder(this)
		.setTitle(R.string.dd_delete_step)
		.setMessage(getString(R.string.dd_do_you_want_to_delete, selectedStep.getTitle()))
		.setIcon(android.R.drawable.ic_dialog_alert)
		.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
		    public void onClick(final DialogInterface dialog, final int whichButton) {
		        //User clicked yes
		    	deleteStep(selectedStep);
		    }
		 })
		 .setNegativeButton(android.R.string.no, null).show();

	    return true;
	}
	
	@Override
	protected void onResume() {
		super.onResume();
			
		final int activityId = mActivity.getId();
        mSteps = new ArrayList<Step>(mStepService.getOrderedSteps(activityId));
        
        adapter = new IconicAdapter();
        setListAdapter(adapter);
        
        Toast.makeText(this, getString(R.string.steplist_info), Toast.LENGTH_LONG).show();
    }
}